<template>
  <el-button type="primary" @click="add">新增用户</el-button>
  <el-button type="danger" @click="batchDel">批量删除</el-button>

  <el-table
      ref="multipleTableRef"
      :data="userList"
      row-key="id"
      style="width: 100%"
      @selection-change="handleSelectionChange">

    <el-table-column type="selection" :selectable="selectable"/>
    <el-table-column label="序号" type="index" width="80px"/>
    <el-table-column property="loginAct" label="账号"/>
    <el-table-column property="name" label="姓名" width="80px"/>
    <el-table-column property="phone" label="手机号" />
    <el-table-column property="email" label="邮箱" />
    <el-table-column property="createTime" label="创建时间"/>
    <el-table-column label="操作" show-overflow-tooltip>
      <template #default="scope">
        <el-button type="primary" @click="view(scope.row.id)">详情</el-button>
        <el-button type="success" @click="edit(scope.row.id)">编辑</el-button>
        <el-button type="danger" @click="del(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
      background layout="prev, pager, next"
      :page-size="pageSize"
      :total="total"
      @prev-click="toPage"
      @next-click="toPage"
      @current-change="toPage"
  >
  </el-pagination>

  <el-dialog v-model="userDialogVisible" :title="userQuery.id>0 ? '编辑用户':'新增用户' " width="50%" center draggable>
    <el-form ref="userRefForm" :model="userQuery" label-width="15%" :rules="userRules">
      <el-form-item label="账号" prop="loginAct">
        <el-input  v-model="userQuery.loginAct" />
      </el-form-item>

      <el-form-item label="密码" v-if="userQuery.id>0">
        <el-input type="password" v-model="userQuery.loginPwd" />
      </el-form-item>
      <el-form-item label="密码" prop="loginPwd" v-else>
        <el-input type="password" v-model="userQuery.loginPwd" />
      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <el-input v-model="userQuery.name" />
      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <el-input v-model="userQuery.phone" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userQuery.email" />
      </el-form-item>

      <el-form-item label="账号是否过期" prop="accountNoExpired">
        <el-select v-model="userQuery.accountNoExpired" placeholder="请选择" style="width: 100%">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>

      <el-form-item label="密码是否过期" prop="credentialsNoExpired">
        <el-select v-model="userQuery.credentialsNoExpired" placeholder="请选择" style="width: 100%">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>

      <el-form-item label="账号是否锁定" prop="accountNoLocked">
        <el-select v-model="userQuery.accountNoLocked" placeholder="请选择" style="width: 100%">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
        </el-select>
      </el-form-item>

      <el-form-item label="账号是否启用" prop="accountEnabled">
        <el-select v-model="userQuery.accountEnabled" placeholder="请选择" style="width: 100%">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="userDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="userSubmit">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {doDelete, doGet, doPost, doPut} from "../http/httpRequest.js";
import {massageTip, messageConfirm} from "../utils/util.js";

export default {
  inject: ['reload'],
  name: 'UserView',
  data(){
    return {
      userList: [{}],
      pageSize: 0,
      total: 0,
      userDialogVisible: false,
      userQuery: {},
      options: [
        {label:'是',value:1},
        {label:'否',value:0},
      ],
      selectData: [],

      // 定义用户验证规则
      userRules:{
        loginAct: [
          { required: true, message: '请输入账号', trigger: 'blur' },
        ],
        loginPwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '密码长度6-12', trigger: 'blur' }
        ],
        name:[
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { pattern: /^[\u4e00-\u9fa5]+$/ ,message: '姓名必须是中文',trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/ ,message: '手机号格式有误',trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,message: '邮箱格式有误',trigger: 'blur' }
        ],
        accountNoExpired: [
          { required: true, message: '请选择账号是否可用', trigger: 'blur' },
        ],
        credentialsNoExpired: [
          { required: true, message: '请选择密码是否过期', trigger: 'blur' },
        ],
        accountNoLocked: [
          { required: true, message: '请选择账号是否被锁定', trigger: 'blur' },
        ],
        accountEnabled: [
          { required: true, message: '请选择是否启用该账号', trigger: 'blur' },
        ]
      }
    }
  },

  mounted() {
    this.getData(1)
  },

  methods:{
    // 勾选/取消勾选出发该函数
    handleSelectionChange(selectData){
      this.selectData=[]
      selectData.forEach(data=>{

        let userId = data.id;
        this.selectData.push(userId)
      })
      console.log(this.selectData)
    },

    // 查询用户列表数据
    getData(current){
      doGet('/api/users',{
        // 当前查询的页数
        current: current
      }).then((resp)=>{
        if (resp.data.code===200){
          this.userList=resp.data.data.list;
          this.pageSize=resp.data.data.pageSize;
          this.total=resp.data.data.total;
        }
      })
    },
    // 分页函数
    toPage(current){
      this.getData(current)
    },
    // 查询用户详情
    view(id){
      console.log(id);
      this.$router.push('/dashBoard/user/'+id)
    },
    // 新增用户
    add(){
      this.userQuery={}
      this.userDialogVisible=true
    },
    // 用户新增提交
    userSubmit(){
      let formData = new FormData();
      for (let fieId in this.userQuery) {
        formData.append(fieId,this.userQuery[fieId])
      }
      this.$refs.userRefForm.validate((isValid)=>{
        if (isValid){
          if (this.userQuery.id>0){
            // 编辑用户信息
            doPut('/api/user',formData).then((resp)=>{
              if (resp.data.code===200){
                massageTip('编辑成功','success')
                // 页面刷新
                this.reload()
              }else {
                massageTip('编辑失败','error')
              }
            })
          }else {
            // 新增用户信息
            doPost('/api/user',formData).then((resp)=>{
              if (resp.data.code===200){
                massageTip('提交成功','success')
                // 页面刷新
                this.reload()
              }else {
                massageTip('提交失败','error')
              }
            })
          }
        }
      })
    },

    // 编辑用户
    edit(id){
      this.userDialogVisible=true
      this.editUser(id)
    },
    editUser(id){
      doGet('/api/user/'+id,{}).then((resp)=>{
        if (resp.data.code===200){
          this.userQuery=resp.data.data;
          this.userQuery.loginPwd=""
        }
      })
    },

    // 删除用户信息
    del(id){
      messageConfirm('您确认要删除吗').then(()=>{
        doDelete('/api/user/'+id,{}).then((resp)=>{
          if (resp.data.code===200){
            massageTip('删除成功','success')
            this.reload();
          }else {
            massageTip('删除失败','error')
          }
        })
      }).catch(()=>{
        massageTip('取消删除','warning')
      })
    },

    // 用户批量删除
    batchDel(){
      if (this.selectData.size<=0){
        massageTip('请选择要删除的用户','warning')
        return;
      }

      // 确认删除
      messageConfirm('您确认要删除这些数据吗？').then(()=>{
        let ids= this.selectData.join(',');
        doDelete('/api/user/',{
          ids: ids
        }).then((resp)=>{
          if (resp.data.code===200){
            massageTip('批量删除成功','success')
            this.reload();
          }else {
            massageTip('批量删除失败','error')
          }
        })
      }).catch(()=>{
        massageTip('取消批量删除','warning')
      })
    }
  }
}
</script>

<style scoped>
.el-table {
  margin-top: 12px;
}
.el-pagination {
  margin-top: 12px;
  float: right;
}
</style>